package cn.czg.cms.mapper;

import cn.czg.cms.entity.Comment;
import cn.czg.cms.entity.dto.SimpleCom;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

@Mapper
public interface CommentMapper extends BaseMapper<Comment> {

    @Select("""
                SELECT * FROM comment
                WHERE post_id = #{postId} AND parent_id = 0 AND status = 1
                ORDER BY created_at DESC
                LIMIT #{offset}, #{limit}
            """)
    List<Comment> selectRootComments(@Param("postId") Long postId,
                                     @Param("offset") int offset,
                                     @Param("limit") int limit);
//
//    @Select("""
//                SELECT * FROM comment
//                WHERE parent_id = #{parentId} AND status = 1
//                ORDER BY created_at ASC
//            """)
//    List<Comment> selectReplies(@Param("parentId") Long parentId);


    @Select("""
                SELECT * FROM comment
                WHERE FIND_IN_SET(#{parentId}, parent_ids) AND status = 1
                ORDER BY created_at ASC
            """)
    List<Comment> selectReplies(@Param("parentId") Long parentId);

    @Select("""
                <script>
                SELECT * FROM comment
                WHERE status = 1
                  AND (
                    <foreach collection="rootIds" item="id" separator=" OR ">
                      FIND_IN_SET(#{id}, parent_ids)
                    </foreach>
                  )
                ORDER BY created_at ASC
                </script>
            """)
    List<Comment> selectDescendantsByParentIds(@Param("rootIds") List<Long> rootIds);


    @Select("""
                <script>
                SELECT
                                               id,
                                               content,
                                               created_at,
                                               avatar
                                           FROM comment
                                           WHERE post_id = #{postId} AND status = 1
                                           ORDER BY created_at DESC
                </script>
            """)
    IPage<SimpleCom> simpleCom(Page<?> page, @Param("postId") Long postId);

}
